<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-submit>
            <el-button :disabled="!canSubmit" @click="submit">提交</el-button>
          </template>
          <template v-slot:filter-check>
            <el-button :disabled="!canCheck" @click="check">审核</el-button>
          </template>
          <template v-slot:filter-revoke>
            <el-button :disabled="!canRevoke" @click="revoke">撤回</el-button>
          </template>
          <template v-slot:filter-reject>
            <el-button :disabled="!canReject" @click="reject">驳回</el-button>
          </template>
          <template v-slot:filter-print>
            <el-button :disabled="!canPrint" @click="print()">打印</el-button>
          </template>
          <template v-slot:filter-excel>
            <el-button :disabled="!canExcel" @click="exportExcel()"
              >导出excel</el-button
            >
          </template>
          <template v-slot:filter-downGroup>
            <el-dropdown>
              <el-button class="el-dropdown-link lightColorBtn">
                下载模板
                <el-icon>
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="$permission('contract:assetTemplate')"
                    @click="downloadTemplate('asset_contract_import_template', '资产合同模板')"
                  >
                    <div>资产合同模板</div>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="$permission('contract:materialTemplate')"
                    @click="downloadTemplate('material_contract_import_template', '物资合同模板')"
                  >
                    <div>物资合同模板</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template v-slot:filter-uploadGroup>
            <el-dropdown>
              <el-button class="el-dropdown-link lightColorBtn">
                导入模板
                <el-icon>
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="$permission('contract:importAsset')"
                  >
                  <el-upload
                    :headers="uploadInfo.headers"
                    :show-file-list="false"
                    :on-error="uploadError"
                    :on-success="importAsset"
                    :before-upload="beforeProductUpload"
                    :action="uploadInfo.assetAction"
                  >
                    <div>资产合同导入</div>
                  </el-upload>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="$permission('contract:importMaterial')"
                  >
                  <el-upload
                    :headers="uploadInfo.headers"
                    :show-file-list="false"
                    :on-error="uploadError"
                    :on-success="importAsset"
                    :before-upload="beforeProductUpload"
                    :action="uploadInfo.materialAction"
                  >
                    <div>物资合同导入</div>
                  </el-upload>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>

        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>

    <contract-modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <contract-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="contract">
import {
  downloadContract,
  changeStatusContract,
  getContractCustomizeListPage,
  deleteContract,
  submitContract,
  checkContract,
  rejectContract,
  revokeContract,
  exportContractList,
  printContractList,
} from '@/api/contract.js'
import { exportTemplateExcel } from '@/api/pub.js'
import { fatchTemplateByCode } from '@/api/base'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import ContractModify from './modify'
import ContractDetail from './details'
import axios from 'axios'
import { ElLoading } from 'element-plus'
const detailList = defineAsyncComponent(() => import('./detailList'))
import _ from 'lodash'

const { proxy } = getCurrentInstance()

const uploadInfo = ref({
  assetAction: axios.defaults.baseURL + '/contract/import/excel/asset',
  materialAction: axios.defaults.baseURL + '/contract/import/excel/product',
  headers: {
    Authorization: proxy.$store.state.user.token,
    'x-auth-token': proxy.$store.state.user.token,
  },
  loading: {},
})

const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    {
      label: '关闭',
      event: handleClose,
      show: true,
    },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('contract:add'),
    },
    {
      type: 'slot',
      value: 'submit',
      show: proxy.$permission('contract:submit'),
    },
    {
      type: 'slot',
      value: 'check',
      show: proxy.$permission('contract:check'),
    },
    {
      type: 'slot',
      value: 'revoke',
      show: proxy.$permission('contract:revoke'),
    },
    {
      type: 'slot',
      value: 'reject',
      show: proxy.$permission('contract:reject'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('contract:printList'),
    },
    {
      type: 'slot',
      value: 'excel',
      show: proxy.$permission('contract:excelList'),
    },
    {
      type: 'button',
      label: '下载附件',
      event: downloadFile,
      show: proxy.$permission('contract:downloadFile'),
    },
    {
      type: 'slot',
      value: 'downGroup',
      show: proxy.$permission('contract:assetTemplate') || 
            proxy.$permission('contract:materialTemplate')
    },
    {
      type: 'slot',
      value: 'uploadGroup',
      show: proxy.$permission('contract:importAsset') || 
            proxy.$permission('contract:importMaterial')
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('contract:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('contract:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '审核',
        event: check,
        show: proxy.$permission('contract:check'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('contract:reject'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('contract:revoke'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('contract:del'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '启用',
        event: enable,
        show: proxy.$permission('contract:enable'),
        ifRender: function (row) {
          return row.isEnable === 0 && row.status === 4
        },
      },
      {
        label: '停用',
        event: enable,
        show: proxy.$permission('contract:disable'),
        ifRender: function (row) {
          return row.isEnable === 1 && row.status === 4
        },
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  id: '',
  title: '',
})
const detailListInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const paramsFlag = ref(true)
const groupFlag = ref(undefined)

const canSubmit = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 1).length
  )
})
const canCheck = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})
const canReject = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})
const canRevoke = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})
const canPrint = computed(() => {
  return !groupFlag.value
})
const canExcel = computed(() => {
  return !groupFlag.value
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function() {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'contract' && el.url === val.url) {
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                detailListInfo.value.visible = false
                advancedSearchInfo.value.visible = false
                preferenceInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.value.visible = true
                  detailInfo.value.id = val.businessId
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})

onDeactivated(() => {
  stopWatch()
})
watch(
  () => tableInfo.value.data,
  (val) => {
    const params = proxy.$route.params
    if (params && params.orderId && paramsFlag.value) {
      const item = _.find(tableInfo.value.data, ['orderNo', params.orderId])
      sessionStorage.setItem('storeRowId', item.id)
      paramsFlag.value = false
    }
  }
)

onMounted(() => {
  const params = proxy.$route.params
  if (params && params.orderId) {
    openDetails(params.orderId)
  }
})

setData()
function setData() {
  let obj = {
    typeValue: {
      label: '类型',
      value: 'typeValue',
      asValue: 'type',
      componentType: 'select-model',
      code: 'asset_scrap_type',
      show: false,
      hidden: true,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'contract_status',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function downloadFile() {
  downloadContract(filterInfo.value.query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function enable(row) {
  //停启用
  let params = {
    id: row.id,
    isEnable: row.isEnable ? 0 : 1,
  }
  changeStatusContract(params).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function handleClose() {
  dialogInfo.value.visible = false
}
function pageInfo(obj) {
  page.value = obj
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  exportContractList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
}
//打印
function printList() {
  fatchTemplateByCode({
    resourceCode: 'contract:printList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  printContractList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
//提交
function submit(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  submitContract(ids).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
//撤回
function revoke(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  revokeContract(ids).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
//删除
function remove(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  deleteContract(ids).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
//驳回
function reject(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  rejectContract(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//审核
function check(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  checkContract(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  let _filterInfo = filterInfo.value
  advancedSearchInfo.value.data = {}
  _filterInfo.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//创建
function create() {
  modifyInfo.value.id = ''
  modifyInfo.value.title = '新增'
  modifyInfo.value.visible = true
}
function update(row) {
  //修改
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.id = row.id
  modifyInfo.value.title = '修改'
  modifyInfo.value.visible = true
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function openDetails(id) {
  detailInfo.value.id = id
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey: 'contractList-com.slip.spd.entity.vo.contract.ContractVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getContractCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}

function downloadTemplate(template, name) {
  exportTemplateExcel(template).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res, name)
    }
  })
}

function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}

function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importAsset(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3500,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 0,
      showClose: true,
    })
  }
}

</script>

<style scoped></style>
